package com.juzipi.demo.config;


import com.juzipi.demo.pojo.User;
import com.juzipi.demo.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


//自定义的
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权 ======》 doGetAuthorizationInfo");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证 =====》 doGetAuthenticationInfo");
        //用户名，密码  数据库查

//        String name = "zhangsan";
//        Integer password = 4321;

        //这里把上面的 authenticationToken 转成 UsernamePasswordToken
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)authenticationToken;

        User user = userService.queryUser(usernamePasswordToken.getUsername());
        if(user == null){
            System.out.println("意义何在");
            return null;
        }

        System.out.println(user);
        //然后根据 usernamePasswordToken 得到传过来的用户名密码
        //再拿这个用户名和密码根数据库里的匹配
        if (usernamePasswordToken.getUsername().equals(user.getUsername())){
            return null;//抛出异常
        }
        //密码认证

        return new SimpleAuthenticationInfo("",user.getPassword(),"");
    }
}
